--
-- Author: shineflag
-- Date: 2017-09-19 16:25:58
-- 工具函数

local utils = {}
----[[
	--当前时间 到北京时区  0时的秒数
--]]
function utils.tomidtime()
    local now = os.time() 
    local beiji = now + 8*3600
    local day_sec = beiji % (3600*24)
    local sec2night = 3600*24 - day_sec
    return sec2night
end


--将一张表转换成 一段lua代码的字符串
function utils.dump(obj)
    local getIndent, quoteStr, wrapKey, wrapVal, dumpObj
    getIndent = function(level)
        return string.rep("\t", level)
    end
    quoteStr = function(str)
        return '"' .. string.gsub(str, '"', '\\"') .. '"'
    end
    wrapKey = function(val)
        if type(val) == "number" then
            return "[" .. val .. "]"
        elseif type(val) == "string" then
            return "[" .. quoteStr(val) .. "]"
        else
            return "[" .. tostring(val) .. "]"
        end
    end
    wrapVal = function(val, level)
        if type(val) == "table" then
            return dumpObj(val, level)
        elseif type(val) == "number" then
            return val
        elseif type(val) == "string" then
            return quoteStr(val)
        else
            return tostring(val)
        end
    end
    dumpObj = function(obj, level)
        if type(obj) ~= "table" then
            return wrapVal(obj)
        end
        level = level + 1
        local tokens = {}
        tokens[#tokens + 1] = "{"
        for k, v in pairs(obj) do
            tokens[#tokens + 1] = getIndent(level) .. wrapKey(k) .. " = " .. wrapVal(v, level) .. ","
        end
        tokens[#tokens + 1] = getIndent(level - 1) .. "}"
        return table.concat(tokens, "\n")
    end
    return dumpObj(obj, 0)
end

--将字符串保存起来
function utils.dump_file(fname, str)
	local file = io.open(fname,"w")
	file:write(str)
	file:flush()
	file:close()
end


--将一张配置表保存
function utils.dump_conf(fname, t)
	local str = utils.dump(t)
	utils.dump_file(fname, "return " .. str .. "\n")
end

function utils.check_num_min(data, min)
    if type(data) ~= "number" or type(min) ~= "number" then 
        return false 
    end
    if data < min then 
        return false 
    end
    return true
end

return utils